angular.module('head-toast', [])

# 如果要弹出toast消息，引入showToast依赖
# 然后 showToast('msg')即可
#
# 还可以指定消息显示的时间
# showToast('another msg', 10000) 则这条消息会被展示10秒钟
# showToast('third msg', -1) 则这条消息会被一直展示，直到被下一条toast消息掩盖
#
# TODO
# 后期支持对不同类型的消息使用不同的样式，例如警告消息使用黄色背景
# showToast('warn msg', type = 'warn')
.service 'showToast', ($rootScope, $ionicBody, $compile) ->
    console.log 'init showToast'

    scope = $rootScope.$new()
    _.defer ->
        template = '''
            <head-toast msg="msg"></head-toast>
        '''
        linkFn = $compile template
        element = linkFn scope
        $ionicBody.get().appendChild element[0] # 插入toast节点至DOM

    (msg, time = 3000, type = 'info') ->
        scope.msg = msg
        if time != -1
            _.delay (->
                scope.msg = undefined
                scope.$digest()
            ), time


.directive 'headToast', ($state) ->
    restrict: 'E'
    scope:
        msg:'='
    templateUrl: 'templates/head-toast/head-toast.html'
    link: ($scope) ->
        $scope.$watch 'msg',(newValue,oldValue)->
            if $scope.msg != undefined
                $scope.toastObj = {show: true, msg: newValue}
            else
                $scope.toastObj = {show: false, msg: undefined}
